<template>
  <div class="captcha-container">
    <el-input
      v-model="inputValue"
      placeholder="请输入验证码"
      :maxlength="4"
      class="captcha-input"
    >
      <template #append>
        <div class="captcha-img" @click="refreshCaptcha" v-html="captchaSvg"></div>
      </template>
    </el-input>
  </div>
</template>

<script setup lang="ts">
import { getCaptchaSVG } from '@/service/module'
import { ref, onMounted, computed } from 'vue'

// 验证码SVG
const captchaSvg = ref('')
const captchaKey = ref('')

// 定义组件属性
const props = defineProps({
  // 是否自动获取验证码
  autoRefresh: {
    type: Boolean,
    default: true
  },
  modelValue: {
    type: String,
    default: ''
  }
})

// 定义组件事件
const emit = defineEmits(['update:modelValue', 'refresh'])

// 计算属性用于双向绑定
const inputValue = computed({
  get() {
    return props.modelValue
  },
  set(value) {
    emit('update:modelValue', value)
  }
})

// 获取验证码
const getCaptcha = async () => {
  try {
    // 这里替换为实际的验证码获取接口
    const response = await getCaptchaSVG()
    captchaSvg.value = response.image
    captchaKey.value = response.key
    emit('refresh', captchaKey.value)
  } catch (error) {
    console.error('获取验证码失败:', error)
  }
}

// 刷新验证码
const refreshCaptcha = () => {
  getCaptcha()
  inputValue.value = ''
}

// 组件挂载时自动获取验证码
onMounted(() => {
  if (props.autoRefresh) {
    getCaptcha()
  }
})
</script>

<style scoped>
.captcha-container {
  display: inline-flex;
  align-items: center;
  width: 100%;
}

.captcha-input {
  width: 100%;
}

.captcha-img {
  height: 30px;
  cursor: pointer;
  display: flex;
  align-items: center;
  padding: 2px 0px;
}

:deep(.captcha-img svg) {
  height: 100%;
}
:deep(.el-input-group__append,
.el-input-group__prepend) {
  padding: 0px;
}
</style>
